package com.example.testone.uiComponents;



import static com.example.testone.uiComponents.WordsButtonAttrs.*;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.RotateDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.animation.LinearInterpolator;

import androidx.annotation.ColorInt;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;

import com.example.testone.R;


/**
 * @Author: dreamgyf
 * @Data: 2021/6/15
 */
public class WordsButton extends AppCompatTextView {

    private final static int DEFAULT_STYLE = STYLE_MAJOR;
    private final static int DEFAULT_SIZE = SIZE_LARGE;
    private final static int DEFAULT_STATUS = STATUS_NORMAL;
    private final static String DEFAULT_LOADING_TEXT = "加载中";

    @StyleInt
    private int mStyle = DEFAULT_STYLE;
    @SizeInt
    private int mSize = DEFAULT_SIZE;
    @StatusInt
    private int mStatus = DEFAULT_STATUS;
    private float mRadius;
    private String mLoadingText = DEFAULT_LOADING_TEXT;

    @ColorInt
    private int mBackgroundColor;
    @ColorInt
    private int mBorderColor;
    private int mBorderWidth;
    @ColorInt
    private int mTextColor;

    private CharSequence mRawText;

    private RotateDrawable mLoadingDrawable;
    private ObjectAnimator mLoadingAnimator;

    public WordsButton(Context context) {
        super(context);
        init(null);
    }

    public WordsButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public WordsButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        initAttrs(attrs);
        setCompoundDrawablePadding(getContext().getResources().getDimensionPixelSize(R.dimen.padding4));
        setGravity(Gravity.CENTER);
        setTypeface(getTypeface(), Typeface.BOLD);
        setFocusable(true);
        setClickable(true);
        renderSize();
        renderStyle();
        renderStatus();
    }


    private void initAttrs(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.WordsButton);
            mStyle = typedArray.getInteger(R.styleable.WordsButton_style, DEFAULT_STYLE);
            mSize = typedArray.getInteger(R.styleable.WordsButton_size, DEFAULT_SIZE);
            mStatus = typedArray.getInteger(R.styleable.WordsButton_status, DEFAULT_STATUS);
            mRadius = typedArray.getDimension(R.styleable.WordsButton_radius, getContext().getResources().getDimension(R.dimen.width11));
            mLoadingText = typedArray.getString(R.styleable.WordsButton_loadingText);
            if (TextUtils.isEmpty(mLoadingText)) {
                mLoadingText = DEFAULT_LOADING_TEXT;
            }
            typedArray.recycle();
        } else {
            mRadius = getContext().getResources().getDimension(R.dimen.width11);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightPx = 0;
        if (mSize == SIZE_LARGE) {
            heightPx = getContext().getResources().getDimensionPixelSize(R.dimen.height22);
        } else if (mSize == SIZE_MEDIUM) {
            heightPx = getContext().getResources().getDimensionPixelSize(R.dimen.height16);
        } else if (mSize == SIZE_SMALL) {
            heightPx = getContext().getResources().getDimensionPixelSize(R.dimen.height12);
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightPx, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void renderSize() {
        requestLayout();
        if (mSize == SIZE_LARGE) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources().getDimensionPixelSize(R.dimen.textsize16));
            setPadding(getContext().getResources().getDimensionPixelSize(R.dimen.padding8),
                    0,
                    getContext().getResources().getDimensionPixelSize(R.dimen.padding8),
                    0);
        } else if (mSize == SIZE_MEDIUM) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources().getDimensionPixelSize(R.dimen.textsize14));
            setPadding(getContext().getResources().getDimensionPixelSize(R.dimen.padding8),
                    0,
                    getContext().getResources().getDimensionPixelSize(R.dimen.padding8),
                    0);
        } else if (mSize == SIZE_SMALL) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources().getDimensionPixelSize(R.dimen.textsize12));
            setPadding(getContext().getResources().getDimensionPixelSize(R.dimen.padding4),
                    0,
                    getContext().getResources().getDimensionPixelSize(R.dimen.padding4),
                    0);
        }
    }

    private void renderStyle() {
        if (mStyle == STYLE_MAJOR) {
            mBackgroundColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            mBorderWidth = 0;
            mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ffffff);
            renderColor();
        } else if (mStyle == STYLE_SIMPLE) {
            mBackgroundColor = ColorUtils.blendARGB(Color.WHITE, ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0), 0.1f);
            mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            mBorderWidth = ScreenUtil.dp2px(1);
            mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            renderColor();
        } else if (mStyle == STYLE_MINOR) {
            mBackgroundColor = Color.TRANSPARENT;
            mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            mBorderWidth = ScreenUtil.dp2px(1);
            mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            renderColor();
        } else if (mStyle == STYLE_TEXT) {
            setBackground(null);

            mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_28bea0);
            ColorStateList textColor = new ColorStateList(new int[][]{{-android.R.attr.state_pressed}, {android.R.attr.state_pressed}},
                    new int[]{mTextColor, getPressedColor(mTextColor)});
            setTextColor(textColor);
        }
    }

    public void setSize(@SizeInt int size) {
        if (size != SIZE_LARGE && size != SIZE_MEDIUM && size != SIZE_SMALL) {
            throw new RuntimeException("size attr error");
        }
        mSize = size;
        renderSize();
    }

    public void setStyle(@StyleInt int style) {
        if (style != STYLE_MAJOR && style != STYLE_SIMPLE && style != STYLE_MINOR && style != STYLE_TEXT) {
            throw new RuntimeException("style attr error");
        }
        mStyle = style;
        renderSize();
        renderStyle();
        renderStatus();
    }

    public void setStatus(@StatusInt int status) {
        if (status != STATUS_NORMAL && status != STATUS_DISABLE && status != STATUS_DANGER && status != STATUS_LOADING) {
            throw new RuntimeException("status attr error");
        }
        mStatus = status;
        renderStyle();
        renderStatus();
    }

    public void setRadius(float radius) {
        mRadius = radius;
        renderColor();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        mRawText = text;
        super.setText(text, type);
    }

    private void renderStatus() {
        resetStatus();
        if (mStatus == STATUS_DISABLE) {
            setAlpha(0.5f);
            setEnabled(false);
        } else if (mStatus == STATUS_DANGER) {
            if (mStyle == STYLE_MAJOR) {
                mBackgroundColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                mBorderWidth = 0;
                mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ffffff);
                renderColor();
            } else if (mStyle == STYLE_SIMPLE) {
                mBackgroundColor = ColorUtils.setAlphaComponent(ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230), 25);
                mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                mBorderWidth = ScreenUtil.dp2px(1);
                mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                renderColor();
            } else if (mStyle == STYLE_MINOR) {
                mBackgroundColor = Color.TRANSPARENT;
                mBorderColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                mBorderWidth = ScreenUtil.dp2px(1);
                mTextColor = ContextCompat.getColor(getContext(), R.color.biz_wg_color_ff6230);
                renderColor();
            }
        } else if (mStatus == STATUS_LOADING) {
            super.setText(mLoadingText);

            if (mStyle == STYLE_MAJOR) {
                mLoadingDrawable = (RotateDrawable) getContext().getDrawable(R.drawable.biz_wg_rotate_loading_white);
            } else if (mStyle == STYLE_SIMPLE || mStyle == STYLE_MINOR) {
                mLoadingDrawable = (RotateDrawable) getContext().getDrawable(R.drawable.biz_wg_rotate_loading_green);
            }
            if (mLoadingDrawable != null) {
                mLoadingAnimator = ObjectAnimator.ofInt(mLoadingDrawable, "level", 0, 10000);
                mLoadingAnimator.setInterpolator(new LinearInterpolator());
                mLoadingAnimator.setDuration(1000);
                mLoadingAnimator.setRepeatCount(-1);
                setCompoundDrawablesWithIntrinsicBounds(mLoadingDrawable, null, null, null);
                mLoadingAnimator.start();
            }

            setAlpha(0.7f);
            setEnabled(false);
        }
    }

    private void resetStatus() {
        setAlpha(1f);
        setEnabled(true);
        super.setText(mRawText);
        mLoadingDrawable = null;
        if (mLoadingAnimator != null) {
            if (mLoadingAnimator.isRunning()) {
                mLoadingAnimator.cancel();
            }
            mLoadingAnimator = null;
        }
    }

    private void renderColor() {
        StateListDrawable background = new StateListDrawable();
        background.addState(new int[]{-android.R.attr.state_pressed}, new BorderLayout.BorderDrawableBuilder()
                .width(mBorderWidth)
                .radius(mRadius)
                .color(mBorderColor)
                .backgroundColor(mBackgroundColor)
                .build());
        background.addState(new int[]{android.R.attr.state_pressed}, new BorderLayout.BorderDrawableBuilder()
                .width(mBorderWidth)
                .radius(mRadius)
                .color(getPressedColor(mBorderColor))
                .backgroundColor(getPressedColor(mBackgroundColor))
                .build());
        setBackground(background);

        ColorStateList textColor = new ColorStateList(new int[][]{{-android.R.attr.state_pressed}, {android.R.attr.state_pressed}},
                new int[]{mTextColor, getPressedColor(mTextColor)});

        setTextColor(textColor);
    }

    @ColorInt
    private int getPressedColor(@ColorInt int baseColor) {
        //blendARGB 混合两个颜色  ratio表示color2的比例
        return ColorUtils.blendARGB(baseColor, Color.BLACK, 0.1f);
    }
}
